package com.protonail.core.licenses;

import com.protonail.core.licenses.license.License;
import com.protonail.core.licenses.license.LicenseType;

import java.time.Instant;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * Created by shenli on 2017/6/21.
 */
public final class LicenseManager {
    private static  String LICENSE_KEY = "l";
    private static  Preferences preferences;

    private static License license;
    public static  LicenseManager INSTANCE;

    public final License getLicense() {
        return license;
    }

    public final void setLicense( License var1) {
        license = var1;
    }

    public final String getFormattedEncryptedLicense() {
        return "";
    }

    public final boolean isLicenseExists() {
        return license != null;
    }

    public final boolean isLicenseActive() {
        return this.isLicenseExists() && LicenseValidator.INSTANCE.validate(license).isValid();
    }

    public final void updateLicense( byte[] encryptedLicense) {
        this.writeLicense(encryptedLicense);
        license = this.readLicense();
    }

    public final void removeLicense() {
        license = (License)null;
        this.writeLicense((byte[])null);
    }

    private final byte[] readEncryptedLicense() {
        return preferences.getByteArray(LICENSE_KEY, (byte[])null);
    }

    private final License readLicense() {
        License result = new License();
        result.setOwner(System.getProperty("user.name"));
        result.setExpiresAt(Instant.MAX);
        result.setType(LicenseType.Enterprise);
        result.setProductUid("keylord");
        result.setUid("1111");
        return result;
    }

    private final void writeLicense(byte[] encryptedLicense) {
        if(encryptedLicense != null) {
            preferences.putByteArray(LICENSE_KEY, encryptedLicense);
        } else {
            preferences.remove(LICENSE_KEY);
        }

        try {
            preferences.flush();
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }
    }

    private LicenseManager() {
        INSTANCE = (LicenseManager)this;
        preferences = Preferences.userRoot().node("kll");
        license = this.readLicense();
    }

    static {
         new LicenseManager();
    }
}